<template>
  <div class="home_sidebar">
    <el-menu
      default-active="2"
      class="el-menu-vertical-demo"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
      :unique-opened="true"
      :router="true"
    >
      <el-submenu :index="index+''" v-for="(item, index) in menuConfig" :key="index">
        <template slot="title">
          <i :class="item.icon"></i>
          <span>{{ item.title }}</span>
        </template>
        <el-menu-item :index="subitem.path" v-for="(subitem,subindex) in item.sub" :key="subindex">{{subitem.title}}</el-menu-item>
      </el-submenu>
    </el-menu>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      menuConfig: [
        {
          title: "商品管理",
          icon: "el-icon-s-tools",
          sub: [
            { title: "商品列表" ,path:'/good'},
            { title: "商品分类" ,path:'/category'},
            { title: "品牌管理" ,path:'/brand'},
            { title: "商品属性管理",path:'/attribute' }
          ]
        },
        {
          title: "订单中心",
          icon: "el-icon-s-management",
          sub: [
            { title: "订单列表" ,path:'/order'}
          ]
        },
        {
          title: "店铺运营",
          icon: "el-icon-service",
          sub: [
            { title: "专题管理" ,path:'/topic'},
            { title: "运营数据" ,path:'/statdata'}
          ]
        },
      ],
    };
  },
   created() {
    let menu = this.$store.state.menu;

    // 把用户权限转换成对象
    let menuObj = menu.reduce((prev, current) => {
      let key = current.path;
      let value = true;
      prev[key] = value;
      return prev;
    }, {});

    let newMenuConfig = []; // 当前用户的菜单配置

    // 循环完整菜单配置数组
    for (let i = 0; i < this.menuConfig.length; i++) {
      // 一级菜单
      let subs = []; // 存放新的二级菜单
      for (let j = 0; j < this.menuConfig[i].sub.length; j++) {
        // 二级菜单
        let newSub = this.menuConfig[i].sub[j];
        if (menuObj[newSub.path]) {
          sub.push(newSub);
        }
      }
      if (sub.length > 0) {
        newMenuConfig.push({
          ...this.menuConfig[i],
          sub,
        });
      }
    }
    //
    this.menuConfig = newMenuConfig;
  },
};
</script>
 
<style lang = "less" scoped>
.home_sidebar {
  display: block;
  position: absolute;
  left: 0;
  top: 70px;
  bottom: 0;
}
</style>